<template>
  <div class="shoe-image-management">
    <!-- 页面标题 -->
    <el-page-header 
      @back="handleBack" 
      content="鞋子图片管理"
      class="page-header"
    />

    <!-- 主要内容区 -->
    <el-card class="main-card">
      <!-- 上传区域 -->
      <div class="upload-section">
        <!-- 使用flex布局使选择框和上传按钮在同一行 -->
        <div class="upload-controls">
          <el-select 
            v-model="selectedShoeName" 
            placeholder="请选择鞋子" 
            class="shoe-select"
            @change="handleShoeChange"
          >
            <el-option 
              v-for="shoe in shoes" 
              :key="shoe.sid" 
              :label="shoe.sname" 
              :value="shoe.sname"
            />
          </el-select>
          
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChangeFile"
            accept="image/*"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择图片
            </el-button>
          </el-upload>
        </div>
        
        <!-- 预览区域 - 增加提交按钮 -->
        <div v-if="imageUrl" class="preview-container">
          <el-image 
            :src="imageUrl" 
            alt="预览图"
            class="preview-image"
            fit="contain"
          />
          <div class="preview-actions">
            <el-button 
              type="success" 
              size="small" 
              class="submit-image"
              @click="submitImage"
              :loading="isSubmitting"
            >
              <el-icon><Check /></el-icon>
              提交图片
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              class="cancel-preview"
              @click="cancelPreview"
            >
              <el-icon><Delete /></el-icon>
              取消预览
            </el-button>
          </div>
        </div>
      </div>

      <!-- 图片列表 -->
      <div class="image-list-section">
        <el-table 
          :data="images" 
          border 
          style="width: 100%"
          :default-sort="{prop: 'spid', order: 'ascending'}"
        >
          <el-table-column 
            type="index" 
            label="序号" 
            width="60"
            align="center"
          />
          <el-table-column 
            label="鞋子名称" 
            width="120"
          >
            <template #default="scope">
              <span class="shoe-name">{{ scope.row.shoes.sname}}</span>
            </template>
          </el-table-column>
          <el-table-column 
            label="图片预览" 
            min-width="300"
            align="center"
          >
            <template #default="scope">
              <el-image 
                :src="scope.row.spurl" 
                alt="鞋子图片"
                class="table-image"
                fit="cover"
                @click="viewImage(scope.row)"
                style="cursor: pointer"
              />
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            width="140"
            align="center"
          >
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewImage(scope.row)"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="showDeleteConfirm(scope.row.spid)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            :page-size="params.pageSize"      
            :total="params.recordCount"      
            v-model:current-page="params.pageNum"  
            @current-change="handleCurrentChange"  
            @prev-click="prevPage"            
            @next-click="nextPage"            
            layout="total,prev,pager,next"    
            background                        
          />
        </div>
      </div>
    </el-card>

    <!-- 图片查看对话框 -->
    <el-dialog 
      v-model="imageDialogVisible" 
      title="图片查看"
      :width="imageDialogWidth"
    >
      <el-image 
        :src="currentImageUrl" 
        alt="图片查看"
        fit="contain"
        class="dialog-image"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { Upload, Delete, View, Check } from '@element-plus/icons-vue';
import { queryPage, insertSave, deleteById, queryAll } from '@/api/PhotosManagement';
import { uploadFileReq } from '@/api/File';

// 响应式数据
const shoes = ref([]);
const images = ref([]);
const selectedShoeName = ref('');
const imageUrl = ref('');
const imageDialogVisible = ref(false);
const currentImageUrl = ref('');
const imageDialogWidth = ref('80%');
const router = useRouter();
const isSubmitting = ref(false); // 提交状态

// 存储本地选择的文件，仅在提交时上传
const selectedFile = ref(null);

// 表单数据
const form = ref({
  spurl: "",
  shoeId: null
});

// 分页相关
const params = ref({
  pageNum: 1,
  pageSize: 5,
  recordCount: 0,
  pageCount: 0
});

// 获取图片列表的API
function searchPage() {
  queryPage(selectedShoeName.value, params.value.pageNum, params.value.pageSize)
    .then(response => {
      images.value = response.list;
      params.value = response.pager;
    })
    .catch(error => {
      console.error('查询图片列表失败:', error);
      ElMessage.error('查询图片列表失败');
    });
}

// 获取鞋子列表
function shoesList() {
  queryAll()
    .then(res => {
      shoes.value = res.list;
    }).catch(err => {
      console.error('初始化查询失败:', err);
    });
}

// 生命周期钩子：加载数据
onMounted(async () => {
  try {
    shoesList();
    searchPage();
  } catch (error) {
    console.error('数据加载失败:', error);
  }
});

// 返回上一页
const handleBack = () => {
  router.back();
  ElMessage.info('返回上一页');
};

// 处理文件选择 - 只在本地预览，不立即上传
function handleChangeFile(uploadFile) {
  // 验证是否选择了鞋子
  if (!selectedShoeName.value) {
    ElMessage.warning('请先选择鞋子');
    return;
  }
  
  // 验证是否有文件
  if (!uploadFile || !uploadFile.raw) {
    ElMessage.warning('请选择图片文件');
    return;
  }
  
  // 仅在本地预览，不立即上传到服务器
  const file = uploadFile.raw;
  selectedFile.value = file; // 暂存文件
  imageUrl.value = URL.createObjectURL(file); // 本地预览
  ElMessage.info('图片已选择，点击提交按钮上传');
}

// 提交图片和表单到服务器
const submitImage = () => {
  // 验证
  if (!selectedFile.value) {
    ElMessage.warning('请先选择图片');
    return;
  }
  
  if (!selectedShoeName.value) {
    ElMessage.warning('请先选择鞋子');
    return;
  }
  
  // 获取选中鞋子的ID
  const selectedShoe = shoes.value.find(shoe => shoe.sname === selectedShoeName.value);
  if (!selectedShoe) {
    ElMessage.warning('未找到选中的鞋子信息');
    return;
  }
  
  isSubmitting.value = true;
  
  // 1. 先上传图片文件
  const formData = new FormData();
  formData.append("file", selectedFile.value);
  
  uploadFileReq(formData)
    .then(imageUrl => {
      // 2. 图片上传成功后，提交表单数据
      return insertSave({
        spurl: imageUrl,
        shoeId: selectedShoe.sid
      });
    })
    .then(response => {
      ElMessage.success('图片和表单提交成功');
      // 重置状态
      cancelPreview();
      // 刷新图片列表
      searchPage();
    })
    .catch(error => {
      ElMessage.error('提交失败，请重试');
      console.error('提交失败:', error);
    })
    .finally(() => {
      isSubmitting.value = false;
    });
};

// 取消预览，清除本地文件
const cancelPreview = () => {
  imageUrl.value = '';
  selectedFile.value = null; // 清除暂存的文件
  form.value.spurl = "";
  form.value.shoeId = null;
};

// 查看图片
const viewImage = (image) => {
  currentImageUrl.value = image.spurl;
  imageDialogVisible.value = true;
};

// 显示删除确认对话框
const showDeleteConfirm = (spid) => {
  ElMessageBox.confirm(
    '确定要删除这张图片吗？此操作不可恢复',
    '删除确认',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    }
  )
  .then(() => {
    deleteImage(spid);
  })
  .catch(() => {
    // 用户取消操作
  });
};

// 删除图片
const deleteImage = (spid) => {
  deleteById(spid)
    .then(response => {
      searchPage();
      ElMessage.success('图片已成功删除');
    })
    .catch(error => {
      ElMessage.error('删除失败');
      console.error(error);
    });
};

// 处理鞋子选择变化
const handleShoeChange = () => {
  // 切换鞋子时清除已选图片
  cancelPreview();
  params.value.pageNum = 1;
  searchPage();
};

// 分页事件处理
const handleCurrentChange = (val) => {
  params.value.pageNum = val;
  searchPage();
};

const prevPage = () => {
  if (params.value.pageNum > 1) {
    params.value.pageNum--;
    searchPage();
  }
};

const nextPage = () => {
  if (params.value.pageNum < params.value.pageCount) {
    params.value.pageNum++;
    searchPage();
  }
};
</script>

<style scoped>
.shoe-image-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.main-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.upload-section {
  padding: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

/* 控制选择框和上传按钮在同一行 */
.upload-controls {
  display: flex;
  align-items: center;
  gap: 15px; /* 两个控件之间的间距 */
  margin-bottom: 20px;
}

.shoe-select {
  width: 300px;
}

.image-uploader {
  flex-shrink: 0; /* 防止按钮被压缩 */
}

.preview-container {
  margin-top: 15px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.preview-image {
  width: 500px;
  height: 300px;
  border: 1px dashed #ccc;
  border-radius: 4px;
}

.preview-actions {
  display: flex;
  gap: 10px;
}

.submit-image {
  margin-right: 5px;
}

.cancel-preview {
  margin-left: 5px;
}

.image-list-section {
  padding: 0 20px 20px;
}

.table-image {
  width: 100%;
  max-width: 500px;
  height: 150px;
  border-radius: 4px;
}

.shoe-name {
  font-size: 14px;
  white-space: normal;
  word-break: break-all;
}

.dialog-image {
  width: 100%;
  max-height: 80vh;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
  padding-right: 10px;
}

/* 表格样式优化 */
:deep(.el-table__header-wrapper th),
:deep(.el-table__body-wrapper td) {
  vertical-align: middle;
}

/* 图标按钮样式调整 */
:deep(.el-button--small .el-icon) {
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .upload-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .shoe-select {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .preview-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .preview-image {
    width: 100%;
    height: auto;
  }
  
  .table-image {
    height: 100px;
  }
  
  .image-dialog-width {
    width: 95%;
  }
  
  .image-list-section {
    overflow-x: auto;
  }
  
  .pagination-container {
    text-align: left;
    padding-left: 10px;
  }
}
</style>
    